<?php
/**
 * 优惠券 api 接口
 * @author maniac
 */

namespace app\api\controller\v1;

use app\common\model\CouponGenerate;
use app\common\model\CouponReceive;
use app\common\model\MemberQy;
use app\common\model\VerificationLog;
use app\common\service\Qrcode;
use app\facade\Coupon AS CouponFacade;
use app\facade\Goods AS GoodsFacade;
use app\facade\CouponMe AS CouponMeFacade;
use app\common\model\Gift AS GiftModel;
use app\common\model\GoodSku AS GoodSkuModel;
use app\facade\Gift AS GiftFacade;
use app\common\model\Buycar as BuycarModel;
use app\common\model\Coupon as CouponModel;
use think\Db;
use think\exception\ErrorException;

class Coupon extends Base
{
    //用户端 优惠券列表
    public function couponList(){
        $user_id = $this->checkUserToken();
//        $user_id = 4;
        $limit = input('limit');
        $page = input('page');
        $type    = input('type');//1已领取 2已使用 3已过期
        $data = new CouponReceive();
        //已领取
        if ($type == 1){
            $data = $data->where("pend",'>',time())->where("status",0);
        }

        //已使用
        if ($type == 2){
            $data = $data->where("status",1);
        }
        //已过期
        if ($type == 3){
            $data = $data->where("pend",'<',time())->where("status",0);
        }

        $data = $data->with(['coupon'=>function($query){
                    return $query->field('id,coupon_name,description,offset_price,limit_price');
                }])->where("member_id",$user_id)->field('id,coupon_id,coupon_generate_id,status,member_id')
                ->append(['number','coupon_pbegin','coupon_type','coupon_pend'])->limit(($page-1)*$limit,$limit)
                ->group('coupon_id')->select();

        return j(0,'成功',$data);
    }
    //优惠券详情
    public function couponDetails(){
        $user_id = $this->checkUserToken();
        $id = input('coupon_id');
        $data = CouponModel::get($id)->append(['pend_txt','pbegin_txt','image_uri']);
        $data['user_id'] = $user_id;
        return j(0,'成功',$data);
    }
    //获取核销码
    public function obtainCode(){
        $this->checkUserToken();
        $id = input('coupon_generate_id');
        $data = CouponGenerate::field('id,verification_code')->get($id);
        $where = ["verification_code"=>$data['verification_code'],"time"=>(time() + 30)]; //三十秒
        $data['img'] = Qrcode::generateQrcode(json_encode($where));
        return j(0,'成功',$data);
    }
    //领取优惠券
    public function receiveCoupon(){
        $member_id = $this->checkUserToken();
//        $member_id = 1;
        $staff_id = input('staff_id');
        $coupon_id = input('coupon_id');
        $url_time = input('url_time');

        $coupon = CouponModel::field('id,pend')->get($coupon_id);
        if (empty($coupon)){
            return j(1,'优惠券已失效');
        }
        $coupon_generate= CouponGenerate::where("coupon_id",$coupon_id)->where("staff_id",$staff_id)->where("receive_status",0)
            ->where("is_release",1)->find();
        if (empty($coupon_generate)){
            return j(1,'优惠券已被领取完');
        }
        $memberCoupon = CouponReceive::where("staff_id",$staff_id)->where("member_id",$member_id)->where('coupon_id',$coupon_id)
            ->where('url_time',$url_time)->field('id')->find();
        if (!empty($memberCoupon)){
            return j(1,"已领取");
        }
        CouponReceive::create([
            'coupon_generate_id' => $coupon_generate['id'],
            'staff_id' => $staff_id,
            'member_id' => $member_id,
            'coupon_id' => $coupon_id,
            'pend' => $coupon['pend'],
            'receive_time' => time(),
            'url_time' => $url_time
        ]);
        $coupon_generate->receive_status = 1;
        if ($coupon_generate->save()){
            return j(0,'领取成功');
        }
        return j(1,'领取失败');
    }
    //领取用户转赠优惠券
    public function receiveTransferCoupon(){
        $member_id = $this->checkUserToken();//领取人id
        $user_id = input('user_id');//转赠人id
        $coupon_id = input('coupon_id');//转赠优惠券id
        $coupon = CouponModel::field('id')->get($coupon_id);
        if (empty($coupon)){
            return j(1,'优惠券已失效');
        }
        $transfer_coupon = CouponReceive::where("member_id",$user_id)->where("coupon_id",$coupon_id)->where("status",0)->find();
        if (empty($transfer_coupon)){
            return j(1,'优惠券已被使用');
        }
        if ($transfer_coupon['pend'] < time ()){
            return j(1,'优惠券已过期');
        }
        CouponGenerate::where("id",$transfer_coupon['coupon_generate_id'])->update([
            'transfer_status' => 1,
            "transfer_id" => $member_id
        ]);
        CouponReceive::create([
            'coupon_generate_id' => $transfer_coupon['coupon_generate_id'],
            'staff_id' => $transfer_coupon['staff_id'],
            'member_id' => $member_id,
            'coupon_id' => $coupon_id,
            'pend' => $transfer_coupon['pend'],
            'receive_time' => time()
        ]);
        $transfer_coupon->transfer_id = $member_id;
        $transfer_coupon->status = 2;
        if ($transfer_coupon->save()){
            return j(0,'领取成功');
        }
        return j(1,'领取失败');
    }
    //核销优惠券
    public function verificationCoupon(){
        $staff_id = $this->checkUserToken();
        $verification = input('verification_code');
        $verification = json_decode($verification,true);
        $verification_code = $verification["verification_code"];
        $time = $verification["time"];
        if (time() > $time){
            return j(1,'核销码失效,请重新获取');
        }
        Db::startTrans();
        try {
            $verification_coupon = CouponGenerate::where("verification_code",$verification_code)->field('id,status,coupon_id')->find();
            if (empty($verification_coupon)){
                return j(1,'优惠劵不存在');
            }
            $coupon = CouponModel::where("id",$verification_coupon['coupon_id'])->field('id')->find();
            if (empty($coupon)){
                return j(1,'核销失败');
            }
            $data = CouponReceive::where('coupon_generate_id',$verification_coupon['id'])->where('status',0)->field('id,status,pend,coupon_id,member_id')->find();
            if ($data['pend'] < time()) {
                return j(1,'优惠劵已过期');
            }
            if ($data['status'] == 1){
                return j(1,'优惠劵已被使用');
            }
            if ($data['status'] == 2){
                return j(1,'优惠劵已被转赠');
            }
            $data->status = 1;
            $data->reviewed_time = time();
            if ($data->save()){
                $verification_coupon->status = 1;
                $verification_coupon->reviewed_time = time();
                if ($verification_coupon->save()){
                    $this->couponVerificationLog($staff_id,$data['coupon_id'],$verification_coupon['id'],$data['member_id']);
                    Db::commit();
                    return j(0,'核销成功');
                }
            }
            Db::rollback();
            return j(1,'核销失败');
        } catch (ErrorException $errorException) {
            Db::rollback();
            return j(1,'核销失败',$errorException->getMessage());
        }

    }
    //核销记录
    public function couponVerificationLog($staff_id,$coupon_id,$verification_coupon_id,$member_id){
        VerificationLog::create([
            'staff_id' => $staff_id,
            'coupon_id' => $coupon_id,
            'verification_coupon_id' => $verification_coupon_id,
            'member_id' => $member_id
        ]);
        return true;
    }
    //员工端优惠券列表
    public function staffCouponList(){
        $user_id = $this->checkUserToken();
//        $user_id = 1;
        $limit = input('limit');
        $page = input('page');
        $type    = input('type');//1已领取 2已发放 3已核销
        //已领取
        if ($type == 1){
            $data = new CouponGenerate();
            $cc_id = [];
            $vv = $data->where("is_release",1)->where("pend",'>',time())->append(['yg_number'])
                ->group('coupon_id')->where("staff_id",$user_id)->select();
            foreach ($vv as $key => $value){
                if ($value['yg_number'] > 0){
                    $cc_id[] = $value['id'];
                }
            }
            $data = $data->where("id",'in',$cc_id)->with(['coupon'=>function($query){
                    return $query->field('id,coupon_name,description,offset_price,limit_price,coupon_type,share_img')->append(['image_uri']);
                }])->field('id,coupon_id,staff_id,member_id')
                ->append(['yg_number','coupon_pbegin','coupon_type','coupon_pend'])
                ->limit(($page-1)*$limit,$limit)->select();
        }

        //已发放
        if ($type == 2){
            $data = new CouponReceive();
            $data = $data->field('status,id,coupon_id,staff_id,member_id')->where("status",'neq',2)->append(['yg_numbers','coupon_pbegin','coupon_type','coupon_pend','member_info'])
                ->group('member_id,coupon_id');
        }
        //已核销
        if ($type == 3){
            $data = new CouponReceive();
            $data = $data->where("status",1)->append(['yg_hx_numbers','coupon_pbegin','coupon_type','coupon_pend','member_info'])
                ->group('member_id,coupon_id')->field('id,coupon_id,staff_id,member_id,status,reviewed_time');
        }
        //未核销
        if ($type == 4){
            $data = new CouponReceive();
            $data = $data->where("status",0)->append(['yg_number','coupon_pbegin','coupon_type','coupon_pend','member_info'])
                ->group('coupon_id')->field('id,coupon_id,staff_id,member_id,status');
        }
        if ($type != 1){
            $data = $data->with(['coupon'=>function($query){
                return $query->field('id,coupon_name,description,offset_price,limit_price,coupon_type,share_img')->append(['image_uri']);
            }])->where("staff_id",$user_id)->limit(($page-1)*$limit,$limit)->select();
        }

        $count['received'] = CouponGenerate::where("is_release",1)->where("receive_status",0)->where("pend",'>',time())->where("staff_id",$user_id)->count('id');
        $count['issued'] = CouponReceive::where("staff_id",$user_id)->count('id');
        $count['reviewed'] = CouponReceive::where("staff_id",$user_id)->where("status",1)->count('id');
        $count['not_reviewed'] = CouponReceive::where("staff_id",$user_id)->where("status",0)->count('id');
        return j(0,'成功',[
            'data' => $data,
            'count'=> $count
        ]);
    }
    public function object_to_array($obj) {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)object_to_array($v);
            }
        }
        return $obj;
    }
    //员工端搜素优惠券
    public function searchCouponList(){
        $user_id = $this->checkUserToken();
        $name = input('name');
        $start_time = input('start_time');
        $end_time = input('end_time');
        $type = input('type');
        $limit = input('limit');
        $page = input('page');
        $member_id = [];
        //已发放
        $data = new CouponReceive();
        if (!empty($name)){
            $member = \app\common\model\Members::where("nickname","like","%".$name."%")->field('id')->select();
            foreach ($member as $key => $value){
                $member_id[] = $value['id'];
            }
            $data = $data->where("member_id","in",$member_id);
        }
        if (!empty($start_time)){
            $data = $data->where("receive_time",">=",$start_time);
        }
        if (!empty($end_time)){
            $data = $data->where("receive_time","<=",$end_time);
        }
        //已发放
        if ($type == 2){
            $data = $data->field('status')->append(['yg_numbers','coupon_pbegin','coupon_type','coupon_pend','member_info'])
                ->group('member_id,coupon_id');
        }
        //已核销
        if ($type == 3){
            $data = $data->where("status",1)->append(['yg_hx_numbers','coupon_pbegin','coupon_type','coupon_pend','member_info'])
                ->group('member_id,coupon_id')->field('status,reviewed_time');
        }
        //未核销
        if ($type == 4){
            $data = $data->where("status",0)->append(['yg_number','coupon_pbegin','coupon_type','coupon_pend','member_info'])
                ->group('coupon_id')->field('status');
        }
        $data = $data->with(['coupon'=>function($query){
            return $query->field('id,coupon_name,description,offset_price,limit_price,coupon_type');
        }])->where("staff_id",$user_id)->field('id,coupon_id,staff_id,member_id')
            ->limit(($page-1)*$limit,$limit)->select();

        return j(0,'成功',$data);
    }

}
